package com.thinvent.workflow.web.interceptor;

import com.thinvent.workflow.common.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求日志拦截器
 */
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("收到请求：{} {}", request.getMethod(), request.getRequestURI());
        // 在此处可加入认证、限流等逻辑
        logger.info("来自 IP [{}] 的请求调用了 工作流 服务", IpUtils.getClientIp(request));
        return true; // 返回 false 则中断请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        // Controller 方法执行后调用
        logger.info("请求处理完成：{} {}", request.getMethod(), request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        // 请求全部完成后调用（包括视图渲染）
        if (ex != null) {
            logger.error("请求过程中发生异常", ex);
        }
        logger.info("请求结束：{} {}，响应状态：{}", request.getMethod(), request.getRequestURI(), response.getStatus());
    }
}
